<?php
class Category extends Zend_Db_Table
{
    protected $_name = 'categories';
    
    
    public function getChildren($parentId = -1, $type = 'product')
    {
        $rowset = $this->fetchAll("parent_id='$parentId' AND type='$type'", 'sort_id');
        $rowArr = $rowset->toArray();

        $children = array();
        foreach ($rowArr as $row) {
            $row['children'] = $this->getChildren($row['id'], $type);
            $children[] = $row;
        }
        
        return $children;
    }
    
    
    public function getFirstChild($parentId = -1)
    {
        $tableName = $this->_db->quoteIdentifier($this->_name);
        $sql = "
            SELECT id 
            FROM $tableName 
            WHERE $tableName.parent_id='$parentId' 
            ORDER BY sort ASC
        ";
        $childId = $this->_db->fetchOne($sql);
        return $childId;
    }
    

    
    public function getMaxSort($parentId, $type = 'product')
    {
        $tableName = $this->_db->quoteIdentifier($this->_name);
        $sql = "
            SELECT MAX(sort_id) 
            FROM $tableName 
            WHERE $tableName.parent_id='$parentId'
                AND type='$type'
        ";
        $maxSortId = $this->_db->fetchOne($sql);
        return $maxSortId;
    }
    
    
    public function getAncestors($parentId)
    {        
        $ancestors = array();
        while ($parentId != '-1') {
            $parentCategory = $this->fetchRow("id='$parentId'");
            $ancestors[] = $parentCategory;
            $parentId = $parentCategory->parent_id;
        }
        $ancestors = array_reverse($ancestors);
        return $ancestors;
    }
}
